/*
 * tc.c
 *
 *  Created on: Sep 14, 2013
 *      Author: Ken Arok
 */

#include "config_board.h"

#if BOARD_2_1_USED

#include "gpio.h"
#include "timers_hw.h"
#include "tc.h"

/* Heart beat CPU. */
static volatile uint8_t _hb = 0;

/** \brief Initialize Timer/Counter 0.
 *
 */
static void tc0_init(void);

/** \brief Initialize Timer/Counter 1.
 *
 */
static void tc1_init(void);

/* ----------------------------------------------------------------------------------- */

void timer_counter_init(void)
{
	/* Initialize Timer/Counter 0. */
	tc0_init();

	/* Initialize Timer/Counter 1. */
	tc1_init();

	if(cpu_irq_is_enabled() == false) {
		cpu_irq_enable();
	}
}

/* 10 millisecond Timer/Counter. */
ISR(TIMER0_COMP_vect)
{
	uint8_t i;

	_hb++;
	if(_hb == 10) {
		gpio_set_pin_high(LED_HB_GPIO);
	}
	else if (_hb > 60) {
		gpio_set_pin_low(LED_HB_GPIO);
		_hb = 0;
	}

	/* Define code here. */

	for(i = 0; i < 16; i++) {
		if(TimersArray10ms[i]) TimersArray10ms[i]--;
	}

	for(i = 0; i < 16; i++) {
		if(FuncArray10ms[i] != NULL) FuncArray10ms[i](ParamFuncArray10ms[i]);
	}

}

ISR(TIMER1_COMPA_vect)
{
	uint8_t i;

	/* Define code here. */

	for(i = 0; i < 16; i++) {
		if(TimersArray500ms[i]) TimersArray500ms[i]--;
	}

	for(i = 0; i < 16; i++) {
		if(FuncArray500ms[i] != NULL) FuncArray500ms[i](ParamFuncArray500ms[i]);
	}

}


/* ------------------------------------------------------------------------------------ */

static void tc0_init(void)
{
	/* Clock source from clk_io .*/
	ASSR = 0x00;
	/* Clear timer/counter on compare match. */
	TCCR0 |= (1 << WGM01);
	TCCR0 &= ~(1 << WGM00);
	/* 10 msec clear timer period. */
	OCR0 = 144;
	/* Enable Compare Match Interrupt. */
	TIMSK |= (1 << OCIE0);
	/* Start Timer with prescale clock 1024. */
	TCCR0 |= 0x07;
}


static void tc1_init(void)
{
	/* Clear timer/counter 1 A on compare match. */
	TCCR1A &= ~(1 << WGM10);
	TCCR1A &= ~(1 << WGM11);
	TCCR1B &= ~(1 << WGM13);
	TCCR1B |= (1 << WGM12);
	/* 500 msec clear timer period. */
	OCR1A = 7200;
	/* Enable Compare Match InterruptChannel A. */
	TIMSK |= (1 << OCIE1A);
	/* Start Timer with prescale clock 1024. */
	TCCR1B &= 0xF9;
	TCCR1B |= 0x05;
}


#endif /* BOARD_2_1_USED */
